import 'package:flutter/material.dart';

class SizeSelector extends StatefulWidget {
  final List<String> sizes;
  final Function(String) onSizeSelected;
  final EdgeInsets padding;

  const SizeSelector({
    Key? key,
    required this.sizes,
    required this.onSizeSelected,
    this.padding = EdgeInsets.zero,
  }) : super(key: key);

  @override
  _HorizontalSizeSelectorState createState() => _HorizontalSizeSelectorState();
}

class _HorizontalSizeSelectorState extends State<SizeSelector> {
  late String _selectedSize = "";

  @override
  void initState() {
    super.initState();
    //_selectedSize = widget.sizes.first; // 初始化为第一个尺码
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 40,
      width: MediaQuery.of(context).size.width,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: widget.sizes.length,
        itemBuilder: (BuildContext context, int index) {
          String size = widget.sizes[index];
          bool isSelected = _selectedSize == size;

          return GestureDetector(
            onTap: () {
              setState(() {
                //_selectedSize = size;
                _selectedSize = isSelected ? "" : size; // 切换选中状态
              });
              //widget.onSizeSelected(size); // 将选定的尺码传递给父组件
              widget.onSizeSelected(isSelected ? "" : size);
            },
            child: Container(
              constraints: const BoxConstraints(minWidth: 45, minHeight: 45),
              margin: const EdgeInsets.symmetric(horizontal: 4.0),
              padding: widget.padding,
              decoration: BoxDecoration(
                border: Border.all(
                  color: _selectedSize == size ? Colors.black : Colors.grey,
                  width: _selectedSize == size ? 1.5 : 0.5,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),
              child: Center(
                child: Text(
                  size,
                  style: TextStyle(
                    color: _selectedSize == size ? Colors.black : Colors.grey,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

/*

SizeSelector(
      sizes: ['XS', 'S', 'M', 'L', 'XL'], // 尺码列表
      onSizeSelected: (selectedSize) {
        print('Selected size: $selectedSize');
        // 在这里处理选定尺码后的逻辑，比如更新 UI 或者提交选择的尺码等
      },
      padding: EdgeInsets.symmetric(horizontal: 8.0), // 可选的内边距
    );
*/